﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebApplication.BaseClass;

namespace WebApplication.Helper
{
    public static class EntityHelper
    {
        public static T CreateResponseMessage<T>(this IRequestMessageBase requestMessage) where T : ResponseMessageBase
        {
            try
            {
                var tType = typeof(T);
                var responseName = tType.Name.Replace("ResponseMessage", "");
                ResponseMsgType msgType = (ResponseMsgType)Enum.Parse(typeof(ResponseMsgType), responseName);
                return CreateFromRequestMessage(requestMessage, msgType) as T;
            }
            catch (Exception ex)
            {
                throw new WeiXinException("ResponseMessageBase.CreateResponseMessage<T>过程发生异常！", ex);
            }
        }

        private static ResponseMessageBase CreateFromRequestMessage(IRequestMessageBase requestMessage, ResponseMsgType msgType)
        {
            ResponseMessageBase responseMessage = null;
            try
            {
                switch (msgType)
                {
                    case ResponseMsgType.Text:
                        responseMessage = new ResponseMessageBase();
                        break;
                    case ResponseMsgType.News:
                        responseMessage = new ResponesMessageNews();
                        break;
                    case ResponseMsgType.Music:
                        responseMessage = new ResponseMessageMusic();
                        break;
                    case ResponseMsgType.Image:
                        responseMessage = new ResponseMessageImage();
                        break;
                    case ResponseMsgType.Voice:
                        responseMessage = new ResponseMessageVoice();
                        break;
                    case ResponseMsgType.Video:
                        responseMessage = new ResponseMessageVideo();
                        break;
                    default:
                        throw new UnknownRequestMsgTypeException(string.Format("ResponseMsgType没有为{0}提供对应处理程序。", msgType), new ArgumentOutOfRangeException());

                }
                responseMessage.ToUserName = requestMessage.FromUserName;
                responseMessage.FromUserName = requestMessage.ToUserName;
                responseMessage.CreateTime = DateTime.Now;//使用当前最新时间
            }
            catch (Exception ex)
            {
                throw new WeiXinException("CreateFromRequestMessage过程发生异常", ex);
            }
            return responseMessage;
        }
    }
}